<template>
	<view
		class="tui-notice__bar"
		:class="{ 'tui-notice__fixed': isFixed }"
		:style="{
			backgroundColor: backgroundColor,
			paddingTop: padding[0] || 0,
			paddingRight: padding[1] || 0,
			paddingBottom: padding[2] || padding[0] || 0,
			paddingLeft: padding[3] || padding[1] || 0,
			height: scrollable || single ? height + 'rpx' : 'auto',
			top: isFixed ? top : 'auto'
		}"
		@click="onClick"
	>
		<view class="tui-notice__shrink" @tap.stop="leftClick" v-if="isLeft"><slot name="left"></slot></view>

		<view class="tui-notice__wrap" :class="{ 'tui-notice__wrap-scroll': scrollable }" :style="{ height: scrollable && !isNvue ? size + 'rpx' : 'auto' }" ref="tui_notice_box">
			<view :id="elId_box" :class="{ 'tui-notice__content': scrollable, 'tui-notice__content-single': !scrollable && single }">
				<text
					ref="animationEle"
					class="tui-notice__text"
					:id="elId"
					:style="{
						color: color,
						fontSize: size + 'rpx',
						lineHeight: scrollable && !isNvue ? size + 'rpx' : 'normal',
						fontWeight: bold ? 'bold' : '',
						animationDuration: animationDuration,
						'-webkit-animationDuration': animationDuration,
						animationPlayState: webviewHide ? 'paused' : animationPlayState,
						'-webkit-animationPlayState': webviewHide ? 'paused' : animationPlayState,
						animationDelay: animationDelay,
						'-webkit-animationDelay': animationDelay
					}"
					:class="{ 'tui-notice__single': !scrollable && single, 'tui-notice__scrollable': scrollable }"
				>
					{{ content }}
				</text>
			</view>
		</view>

		<view class="tui-notice__shrink" @tap.stop="rightClick" v-if="isRight"><slot name="right"></slot></view>
	</view>
</template>

<script setup>
import { ref, reactive, toRefs, watch, getCurrentInstance, nextTick, onBeforeMount, onMounted, onBeforeUnmount } from 'vue'

const { ctx } = getCurrentInstance()

//APP-NVUE 暂不支持vue3

const emit = defineEmits(['click', 'leftClick', 'rightClick'])

const props = defineProps({
	//通告栏高度
	height: {
		type: [Number, String],
		default: 72
	},
	content: {
		type: String,
		default: ''
	},
	//字体大小 rpx
	size: {
		type: [Number, String],
		default: 28
	},
	color: {
		type: String,
		default: '#ff7900'
	},
	bold: {
		type: Boolean,
		default: false
	},
	backgroundColor: {
		type: String,
		default: '#fff8d5'
	},
	//scrollable为false时使用,['20rpx','30rpx','20rpx','30rpx']=>[上，右，下，左],为了兼容nvue
	padding: {
		type: Array,
		default() {
			return []
		}
	},
	//是否单行
	single: {
		type: Boolean,
		default: false
	},
	//是否滚动，添加后控制单行效果取消
	scrollable: {
		type: Boolean,
		default: false
	},
	//每秒滚动速度（距离） 默认 100px/s
	speed: {
		type: Number,
		default: 100
	},
	//backwards: 动画从头开始播；forwards：动画从结束点开始播
	activeMode: {
		type: String,
		default: 'backwards'
	},
	//是否需要左侧slot内容
	isLeft: {
		type: Boolean,
		default: false
	},
	//是否需要右侧slot内容
	isRight: {
		type: Boolean,
		default: false
	},
	//是否固定在顶部
	isFixed: {
		type: Boolean,
		default: false
	},
	//isFixed为true时top值
	top: {
		type: String,
		// #ifdef H5
		default: '44px',
		// #endif
		// #ifndef H5
		default: '0'
		// #endif
	},
	//自定义参数
	params: {
		type: [Number, String],
		default: 0
	}
})

const elId = `tui_${Math.ceil(Math.random() * 10e5).toString(36)}`
const elId_box = `tui_${Math.ceil(Math.random() * 10e5).toString(36)}`
let isNvue = false
// #ifdef APP-NVUE
isNvue = true
// #endif

const state = reactive({
	elId: elId,
	elId_box: elId_box,
	noticeWidth: 0,
	boxWidth: 0,
	wrapWidth: '',
	webviewHide: false,
	// #ifdef APP-NVUE
	stopAnimation: false,
	// #endif
	isNvue: isNvue,
	animationDuration: 'none',
	animationPlayState: 'paused',
	animationDelay: '0s'
})

watch(
	() => props.scrollable,
	nVal => {
		if (val) {
			nextTick(() => {
				initAnimation()
			})
		}
	}
)

watch(
	() => props.content,
	nVal => {
		nextTick(() => {
			initAnimation()
		})
	}
)

onMounted(() => {
	// #ifdef APP-PLUS
	const pages = getCurrentPages()
	const page = pages[pages.length - 1]
	const currentWebview = page.$getAppWebview()
	currentWebview.addEventListener('hide', () => {
		state.webviewHide = true
	})
	currentWebview.addEventListener('show', () => {
		state.webviewHide = false
	})
	// #endif

	nextTick(() => {
		initAnimation()
	})
})

onBeforeUnmount(() => {
	// #ifdef APP-NVUE
	state.stopAnimation = true
	// #endif
})

const initAnimation = () => {
	if (!props.content || props.content == '') return
	if (props.scrollable) {
		// #ifndef APP-NVUE
		let query = [],
			boxWidth = 0,
			noticeWidth = 0
		let noticeQuery = new Promise((resolve, reject) => {
			uni.createSelectorQuery()
				// #ifndef MP-ALIPAY
				.in(ctx)
				// #endif
				.select(`#${state.elId}`)
				.boundingClientRect()
				.exec(ret => {
					state.noticeWidth = ret[0].width
					resolve()
				})
		})

		if (props.activeMode === 'forwards') {
			let boxQuery = new Promise((resolve, reject) => {
				uni.createSelectorQuery()
					// #ifndef MP-ALIPAY
					.in(ctx)
					// #endif
					.select(`#${state.elId_box}`)
					.boundingClientRect()
					.exec(ret => {
						state.boxWidth = ret[0].width
						resolve()
					})
			})
			query.push(boxQuery)
		}
		query.push(noticeQuery)

		Promise.all(query).then(() => {
			state.animationDuration = `${state.noticeWidth / props.speed}s`
			if (props.activeMode === 'forwards') {
				state.animationDelay = `-${state.boxWidth / props.speed}s`
			}
			setTimeout(() => {
				state.animationPlayState = 'running'
			}, 1000)
		})
		// #endif
	}
}

const { elId, elId_box, webviewHide, isNvue, animationDuration, animationDelay, animationPlayState } = toRefs(state)

const onClick = () => {
	emit('click', {
		params: props.params
	})
}
const leftClick = () => {
	emit('leftClick', {
		params: props.params
	})
}
const rightClick = () => {
	emit('rightClick', {
		params: props.params
	})
}
</script>

<style lang="scss" scoped>
.tui-segmented__control {
	flex: 1;
	/* #ifndef APP-NVUE */
	width: 100%;
	display: flex;
	box-sizing: border-box;
	/* #endif */
	flex-direction: row;
	overflow: hidden;
	/* #ifdef H5 */
	cursor: pointer;
	/* #endif */
}

.tui-segmented__item {
	/* #ifndef APP-NVUE */
	display: inline-flex;
	box-sizing: border-box;
	transition: all 0.1s linear;
	/* #endif */

	flex: 1;
	justify-content: center;
	align-items: center;
	border-style: solid;
	border-left-width: 0;

	/* #ifdef APP-NVUE */
	border-top-width: 0.5px;
	border-bottom-width: 0.5px;
	border-right-width: 0.5px;
	/* #endif */

	/* #ifndef APP-NVUE */
	border-top-width: 1px;
	border-bottom-width: 1px;
	border-right-width: 1px;
	/* #endif */

	position: relative;
}

.tui-segmented__disabled {
	opacity: 0.5;
	/* #ifdef H5 */
	cursor: not-allowed !important;
	/* #endif */
}

.tui-segmented__first {
	border-left-style: solid;
	/* #ifndef APP-NVUE */
	border-left-width: 1px;
	/* #endif */

	/* #ifdef APP-NVUE */
	border-left-width: 0.5px;
	/* #endif */
}
</style>
